﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：宣帅
    //
    // 文件名：OrderDistributionNoSend.cs
    // 文件功能描述：未配送查询，进行配送操作
    // 创建标识：宣帅2009-05-13
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;

using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Enterprise.OrderManage
{
    public partial class OrderDistribute : BasePage
    {
        public OrderDistribute()
        {
            this.ModuleNo = Module.配送单管理.ToString();
        }

        IBLL_Purchase iPurchase = Factory.BLL_Purchase();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Bind();
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            Bind();
        }

        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据 

                txtGoodsName.Text = "";
                txtOutLookc.Text = "";
                txtStartDate.Text = "";
                txtEndDate.Text = "";
                txtHospitalName.Text = "";
                //txtPinyinCode.Text = "";

            }
            Bind();
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                List<HZ.DrugTrade.Model.Distribution> DistributionList = new List<Distribution>();
                List<HZ.DrugTrade.Model.DistributionBatchRecord> DistributionBatchRecordList = new List<DistributionBatchRecord>();
                //DateTime dtDistributeTime = DateTime.Now;
                for (int i = 0; i < this.gvwProduceCatalog.Rows.Count; i++)
                {
                    if (gvwProduceCatalog.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                        if (chk.Checked == true)
                        {

                            //申明两个实体，存放配送的信息
                            HZ.DrugTrade.Model.Distribution aDistribution = new HZ.DrugTrade.Model.Distribution();
                            HZ.DrugTrade.Model.DistributionBatchRecord aDistributionBatchRecord = new HZ.DrugTrade.Model.DistributionBatchRecord();


                            //string strTempDistributeCount = new HZ.Common.ConvertHelper(gvwProduceCatalog.Rows[i].Cells["Dis_DistributeCount"].Value).String;



                            //获得配送量的textbox
                            TextBox txtDis_DisTributeCount = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtDis_DisTributeCount");

                            int? iDistributeCount = new HZ.Common.ConvertHelper(txtDis_DisTributeCount.Text.Trim()).ToInt32;
                            if (iDistributeCount <= 0 || iDistributeCount == null)
                            {
                                HZ.Web.WebUtil.Alert("请填写配送数量！", this);
                                ((TextBox)gvwProduceCatalog.Rows[i].FindControl("txtDis_DisTributeCount")).Focus();
                                return;
                            }
                            aDistribution.DistributeCount = iDistributeCount;

                            //配送明细ID
                            string strOrderDetailID = new HZ.Common.ConvertHelper(gvwProduceCatalog.DataKeys[i].Values[0].ToString()).String;

                            //获取采购总量和已配送量
                            int? PurchaseCount = new HZ.Common.ConvertHelper(gvwProduceCatalog.DataKeys[i].Values[1].ToString()).ToInt32;
                            int? DistributeCount = new HZ.Common.ConvertHelper(gvwProduceCatalog.DataKeys[i].Values[2].ToString()).ToInt32;

                            if (iDistributeCount + DistributeCount > PurchaseCount)
                            {
                                HZ.Web.WebUtil.Alert("第" + (i + 1) + "条记录，配送数量大于采购量，请检查！", this);
                                return;
                            }

                            //获取批号textbox
                            TextBox txtBatchRecordID = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtBatchRecordID");
                            string strBatchRecordID = new HZ.Common.ConvertHelper(txtBatchRecordID.Text.Trim()).String;
                            if (string.IsNullOrEmpty(strBatchRecordID))
                            {
                                HZ.Web.WebUtil.Alert("批号不能为空！", this);
                                ((TextBox)gvwProduceCatalog.Rows[i].FindControl("txtBatchRecordID")).Focus();
                                return;
                            }
                            string strDistributionSerialID = Guid.NewGuid().ToString();

                            aDistribution.DistributionSerialID = strDistributionSerialID;
                            aDistribution.OrderDetailID = strOrderDetailID;
                            aDistribution.DistributeTime = DateTime.Now;
                            aDistribution.IsInvoice = false;
                            aDistributionBatchRecord.BatchRecordID = strBatchRecordID;
                            aDistributionBatchRecord.DistributionSerialID = strDistributionSerialID;

                            DistributionList.Add(aDistribution);
                            DistributionBatchRecordList.Add(aDistributionBatchRecord);
                        }
                    }

                }
                if (DistributionList.Count > 0)
                {
                    int nSuccess = iPurchase.UpdatePurchaseOrderDetail_Distribution_Batch(DistributionList, DistributionBatchRecordList);
                    if (nSuccess == 1)
                    {
                        HZ.Web.WebUtil.Alert("配送成功", this);
                        Bind();

                    }
                    else if (nSuccess == 2)
                    {
                        HZ.Web.WebUtil.Alert("医疗机构已撤回该采购明细！", this);
                        Bind();
                    }
                    else if (nSuccess == 3)
                    {
                        HZ.Web.WebUtil.Alert("该采购明细已配送或拒绝配送,请勿重复操作！", this);
                        Bind();
                    }
                    else if (nSuccess == 0)
                    {
                        HZ.Web.WebUtil.Alert("配送失败", this);
                        Bind();
                    }
                }
            }
            catch (Exception ex)
            {
                PageError("数据库连接失败！", "");
            }
        }




        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            Bind();
        }

        protected void Bind()
        {
            HZ.DrugTrade.Model.Query.PurchaseOrderDetail qryDistribution = new HZ.DrugTrade.Model.Query.PurchaseOrderDetail();
            //qryDistribution.OrderDetailState = 2;//已确认； modfiy by ysm 20130201 注释说明 ： 去除订单确认步骤，无需确认直接配送 ，配送后订单状态为已确认
            qryDistribution.OrderDetailState = 1; //未确认状态 即医疗机构已提交 modfiy ysm 20130201
            qryDistribution.StartTimeFrom = new HZ.Common.ConvertHelper(txtStartDate.Text.Trim()).ToDateTime;
            qryDistribution.StartTimeTo = new HZ.Common.ConvertHelper(txtEndDate.Text.Trim()).ToDateTime;
            qryDistribution.HospitalName = this.txtHospitalName.Text.Trim();
            qryDistribution.CompanyID_PS = CurrentAccount.GetUser().Org.OrgID;
            //qryDistribution.PinyinCode = this.txtPinyinCode.Text.Trim();
            qryDistribution.GoodsName = this.txtGoodsName.Text.Trim();
            qryDistribution.Outlookc = this.txtOutLookc.Text.Trim();
            qryDistribution.PinyinCode = this.txtpinyincode.Text.Trim().ToUpper();
            qryDistribution.Material = this.txtMaterial.Text.Trim();

            qryDistribution.ProjectID = this.ddlProjectid.SelectedValue;
            qryDistribution.SortFields = "ExecuteTime desc,OrderName ASC,HospitalName ASC,GoodsName ASC ";
            //qryDistribution.Append = " orderdetailId in (select orderdetailId from Tb_Distribution where distributestate=0) ";
            //调用方法，执行查询，分页显示产品信息
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalrecord = 0;
            try
            {
                IList<HZ.DrugTrade.Model.View.PurchaseOrderDetail> UndistrbutedList = iPurchase.GetPurchaseOrderDetail_NoDistributeByWhere(qryDistribution, this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out totalrecord);

                gvwProduceCatalog.AutoGenerateColumns = false;
                gvwProduceCatalog.DataSource = UndistrbutedList;
                AspNetPager1.RecordCount = totalrecord;
                gvwProduceCatalog.DataBind();
            }
            catch (Exception ex)
            {
                PageError(ex.Message, "");
            }

            if (gvwProduceCatalog.Rows.Count <= 0)
            {
                btnExport.Visible = false;
            }
        }
        /// <summary>
        ///拒绝配送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSend0_Click(object sender, EventArgs e)
        {
            try
            {
                List<HZ.DrugTrade.Model.PurchaseOrderDetail> PurchaseOrderDetailList = new List<PurchaseOrderDetail>();

                //DateTime dtDistributeTime = DateTime.Now;
                for (int i = 0; i < this.gvwProduceCatalog.Rows.Count; i++)
                {
                    if (gvwProduceCatalog.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                        if (chk.Checked == true)
                        {
                            string Reason = "";
                            TextBox txtReason = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtCompanyRemark");
                            Reason = txtReason.Text.Trim();
                            if (string.IsNullOrEmpty(Reason))
                            {
                                HZ.Web.WebUtil.Alert("请填写拒绝配送理由！", this);
                                ((TextBox)gvwProduceCatalog.Rows[i].FindControl("txtCompanyRemark")).Focus();
                                return;
                            }
                            //申明两个实体，存放配送的信息
                            HZ.DrugTrade.Model.PurchaseOrderDetail aPurchaseOrderDetail = new PurchaseOrderDetail();
                            //配送明细ID
                            string strOrderDetailID = new HZ.Common.ConvertHelper(gvwProduceCatalog.DataKeys[i].Values[0].ToString()).String;
                            aPurchaseOrderDetail.OrderDetailID = strOrderDetailID;
                            aPurchaseOrderDetail.Reason = Reason;
                            PurchaseOrderDetailList.Add(aPurchaseOrderDetail);
                        }
                    }
                }
                if (PurchaseOrderDetailList.Count > 0)
                {
                    int nSuccess = iPurchase.RefuseConfirmPurchaseOrderDetail_Batch(PurchaseOrderDetailList);//没有提供无法拒绝配送接口；
                    if (nSuccess == 1)
                    {
                        HZ.Web.WebUtil.Alert("拒绝配送确认成功！", this);
                        Bind();

                    }
                    else if (nSuccess == 2)
                    {
                        HZ.Web.WebUtil.Alert("该采购明细已配送或拒绝配送,请勿重复操作！", this);
                        Bind();
                    }
                    else if (nSuccess == 0)
                    {
                        HZ.Web.WebUtil.Alert("拒绝配送确认失败！", this);
                        Bind();
                    }
                }
            }
            catch (Exception ex)
            {
                PageError("数据库连接失败！", "");
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            HZ.DrugTrade.Model.Query.PurchaseOrderDetail qryDistribution = new HZ.DrugTrade.Model.Query.PurchaseOrderDetail();
            //qryDistribution.OrderDetailState = 2;//已确认； modfiy by ysm 20130201 注释说明 ： 去除订单确认步骤，无需确认直接配送 ，配送后订单状态为已确认
            qryDistribution.OrderDetailState = 1; //未确认状态 即医疗机构已提交 modfiy ysm 20130201
            qryDistribution.StartTimeFrom = new HZ.Common.ConvertHelper(txtStartDate.Text.Trim()).ToDateTime;
            qryDistribution.StartTimeTo = new HZ.Common.ConvertHelper(txtEndDate.Text.Trim()).ToDateTime;
            qryDistribution.HospitalName = this.txtHospitalName.Text.Trim();
            qryDistribution.CompanyID_PS = CurrentAccount.GetUser().Org.OrgID;
            //qryDistribution.PinyinCode = this.txtPinyinCode.Text.Trim();
            qryDistribution.GoodsName = this.txtGoodsName.Text.Trim();
            qryDistribution.PinyinCode = this.txtpinyincode.Text.Trim().ToUpper();
            qryDistribution.Outlookc = this.txtOutLookc.Text.Trim();
            qryDistribution.Material = this.txtMaterial.Text.Trim();
            qryDistribution.ProjectID = this.ddlProjectid.SelectedValue;
            qryDistribution.SortFields = "ExecuteTime desc,OrderName ASC,HospitalName ASC,GoodsName ASC ";

            int totalrecord = 0;
            IList<HZ.DrugTrade.Model.View.PurchaseOrderDetail> UndistrbutedList = iPurchase.GetPurchaseOrderDetail_NoDistributeByWhere(qryDistribution, 1, 0, out totalrecord);

            DataTable dt = HZ.Data.ModelConvert.GetDataTableFromModel(UndistrbutedList);

            HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwProduceCatalog);
        }

        protected void gvwProduceCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (ddlProjectid.SelectedItem.Value == "0002")
                {
                    e.Row.Cells[4].Text = "自主报价";
                }
                else
                {
                    e.Row.Cells[4].Text = "采购限价";
                }
            }
        }
    }
}
